<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This is a sample module for PyroCMS
 *
 * @author 		Jerel Unruh - PyroCMS Dev Team
 * @website		http://unruhdesigns.com
 * @package 	PyroCMS
 * @subpackage 	Sample Module
 */
class Admin extends Admin_Controller
{
	protected $section = 'commercial_objectives';
	protected $_ci;
	public function __construct()
	{
		parent::__construct();
		$this->_ci = &get_instance();
		// Load all the required classes
		$this->load->library('form_validation');
		$this->load->model('escort_commercial_objectives_m');
		$this->load->model('groups_m');
		$this->load->model('users_m');
		$this->load->model('escort_user_roles_n_benefits_m');
		
		$this->lang->load('commercial_objective');
		// Set the validation rules
		$this->validation_rules = array(
			array(
				'field' => 'commercial_id',
				'label' => 'lang:escort_commercial_objective_commercial_label',
				'rules' => 'trim|max_length[255]|required'
			),
			array(
				'field'	=> 'rate_from',
				'label'	=> 'lang:escort_commercial_objective_rate_from_label'
			),
			array(
				'field' => 'rate_to',
				'label' => 'lang:escort_commercial_objective_rate_to_label',
				'rules' => 'trim'
			),
			array(
				'field' => 'actual_registered',
				'label' => 'lang:escort_commercial_objective_actual_label',
				'rules' => 'trim|required|is_natural'
			),
			array(
				'field' => 'price_per_register',
				'label' => 'lang:escort_commercial_objective_price_label',
				'rules' => 'trim|is_natural|required'
			),
			array(
				'field' => 'active',
				'label' => 'lang:escort_commercial_objective_active_label',
				'rules' => 'trim'
			)
		);

		$this->data->rateFromList = array();
		$this->data->rateToList = array();
		$this->data->priceList = array();
		for ($i = 0; $i < 1000; $i++){
			$this->data->rateFromList[$i] = $i;
			$this->data->rateToList[$i] = $i;
			$this->data->priceList[$i] = $i;
		}
		$commercialGroupId = $this->groups_m->get_by('name', USER_COMMERCIAL)->id;
		$commercials = $this->users_m->get_many_by('group_id', $commercialGroupId);
		$this->data->commercialList = array();
		if($commercials){
			foreach ($commercials as $commercial){
				$user = $this->escort_user_roles_n_benefits_m->get_by('username', $commercial->username);
				if($user){
					$this->data->commercialList[$user->id] = $user->username;
				}
			}
		}

		$discountTypes = $this->_ci->discount_type_entity->getList();
		if($discountTypes){
			foreach ( $discountTypes as $discountType){
				$this->data->discountTypeList[$discountType->id] = $discountType->name;
			}
		}

		$this->template->set_partial('shortcuts', 'admin/partials/shortcuts')
		->append_metadata(js('escort.commercial.js', 'be_commercial_objective'))
		->append_metadata(css('escort.commercial.css', 'be_commercial_objective'));
	}

	/**
	 * List all items
	 */
	public function index()
	{
		// Create pagination links
		$total_rows = $this->_ci->commercial_objective_entity->count();
		$pagination = create_pagination('admin/be_commercial_objective/index', $total_rows);
		// Using this data, get the relevant results
		$commercials = $this->_ci->commercial_objective_entity->getList('',$pagination['limit']);

		//do we need to unset the layout because the request is ajax?
		$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';

		$this->template
		->title($this->module_details['name'])
		->append_metadata(js('admin/filter.js'))
		->set('pagination', $pagination)
		->set('commercials', $commercials);

		$this->input->is_ajax_request() ? $this->template->build('admin/tables/posts', $this->data) : $this->template->build('admin/index', $this->data);
			
	}

	public function create()
	{
		$this->form_validation->set_rules($this->validation_rules);

		if ($this->form_validation->run())
		{
			$commercial_id = $this->input->post('commercial_id');
			$user = $this->escort_user_roles_n_benefits_m->get($commercial_id);
			$id = $this->escort_commercial_objectives_m->insert(array(
				'commercial_id'	=> $this->input->post('commercial_id'),
				'commercial_username'	=> $user->username,
				'commercial_name'	=> $user->name,
				'rate_from'	=> $this->input->post('rate_from'),
				'rate_to'	=> $this->input->post('rate_to'),
				'actual_registered'	=> $this->input->post('actual_registered'),
				'price_per_register'	=> $this->input->post('price_per_register'),
				'active'	=> $this->input->post('active'),
				'created_time'	=> time()
			));
			if ($id)
			{
				do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_create_commercial_objective_action', array($id));
				$this->session->set_flashdata('success', sprintf($this->lang->line('escort_commercial_objective_add_success'), $user->username));
			}
			else
			{
				$this->session->set_flashdata('error', $this->lang->line('escort_commercial_objective_add_error'));
			}
			$this->input->post('btnAction') == 'save_exit' ? redirect('admin/be_commercial_objective') : redirect('admin/be_commercial_objective/edit/' . $id);
		}
		else
		{
			// Go through all the known fields and get the post values
			foreach ($this->validation_rules as $key => $field)
			{
				$commercial->$field['field'] = set_value($field['field']);
			}
		}

		$this->template
		->title($this->module_details['name'], lang('escort_commercial_objective_add_title'))
		->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
		->append_metadata(js('jquery/jquery.tagsinput.min.js'))
		->append_metadata(js('blog_form.js', 'blog'))
		->append_metadata(css('jquery/jquery.tagsinput.css'))
		->set('commercial', $commercial)
		->build('admin/form', $this->data);
	}
	public function edit($id = 0)
	{
		$id OR redirect('admin/be_commercial_objective');
		$commercial = $this->escort_commercial_objectives_m->get($id);
		$commercial OR redirect('admin/be_commercial_objective');
		$this->form_validation->set_rules($this->validation_rules);
		if ($this->form_validation->run())
		{
			$commercial_id = $this->input->post('commercial_id');
			$user = $this->escort_user_roles_n_benefits_m->get($commercial_id);
			$result = $this->escort_commercial_objectives_m->update($id, array(
					'commercial_id'	=> $this->input->post('commercial_id'),
					'commercial_username'	=> $user->username,
					'commercial_name'	=> $user->name,
					'rate_from'	=> $this->input->post('rate_from'),
					'rate_to'	=> $this->input->post('rate_to'),
					'actual_registered'	=> $this->input->post('actual_registered'),
					'price_per_register'	=> $this->input->post('price_per_register'),
					'active'	=> $this->input->post('active')
			));

			if ($result)
			{
				do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_edit_commercial_objective_action', array($id));
				$this->session->set_flashdata(array('success' => sprintf(lang('escort_commercial_objective_edit_success'), $user->username)));
			}
			else
			{
				$this->session->set_flashdata('error', $this->lang->line('escort_commercial_objective_edit_error'));
			}

			// Redirect back to the form or main page
			$this->input->post('btnAction') == 'save_exit' ? redirect('admin/be_commercial_objective') : redirect('admin/be_commercial_objective/edit/' . $id);
		}

		// Go through all the known fields and get the post values
		foreach ($this->validation_rules as $key => $field)
		{
			if (isset($_POST[$field['field']]))
			{
				$commercial->$field['field'] = set_value($field['field']);
			}
		}

		$this->template
		->title($this->module_details['name'], sprintf(lang('escort_commercial_objective_edit_title'), $commercial->commercial_username))
		->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
		->append_metadata(js('jquery/jquery.tagsinput.min.js'))
		->append_metadata(js('blog_form.js', 'blog'))
		->append_metadata(css('jquery/jquery.tagsinput.css'))
		->set('commercial', $commercial)
		->build('admin/form');
	}
	public function delete($id = 0)
	{
		// Delete one
		$ids = ($id) ? array($id) : $this->input->post('action_to');

		// Go through the array of slugs to delete
		if ( ! empty($ids))
		{
			$commercialUsernames = array();
			foreach ($ids as $id)
			{
				// Get the current page so we can grab the id too
				if ($commercial = $this->escort_commercial_objectives_m->get($id))
				{
					$this->escort_commercial_objectives_m->delete($id);
					do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_delete_commercial_objective_action', array($id));
					// Wipe cache for this model, the content has changed
					$this->pyrocache->delete('escort_commercial_objectives_m');
					$commercialUsernames[] = $commercial->commercial_username;
				}
			}
		}

		// Some pages have been deleted
		if ( ! empty($commercialUsernames))
		{
			// Only deleting one page
			if (count($commercialUsernames) == 1)
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('escort_be_discount_delete_success'), $commercialUsernames[0]));
			}
			// Deleting multiple pages
			else
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('escort_be_discount_mass_delete_success'), implode('", "', $commercialUsernames)));
			}
		}
		// For some reason, none of them were deleted
		else
		{
			$this->session->set_flashdata('notice', lang('escort_be_discount_delete_error'));
		}

		redirect('admin/be_commercial_objective');
	}
	public function _check_code($code)
	{
		$this->form_validation->set_message('_check_code', sprintf(lang('escort_be_discount_discount_code_exist_error'), lang('escort_be_discount_title')));
		if($this->escort_discount_tickets_m->get($code)){
			return false;
		}else{
			return true;
		}
	}
	public function generate_code(){
		$length = 6;
		$validCharacters = "abcdefghijklmnopqrstuxyvwzABCDEFGHIJKLMNOPQRSTUXYVWZ1234567890";
		$validCharNumber = strlen($validCharacters);
		$result = "";
		for ($i = 0; $i < $length; $i++) {
			$index = mt_rand(0, $validCharNumber - 1);
			$result .= $validCharacters[$index];
		}
		if($this->_check_code($result)){
			$data = array('code' => $result);
			echo json_encode($data);
			return;
		}else{
			$this->generate_code();
		}
	}
	public function export_whole_list(){
		header("Content-type: application/vnd.ms-excel");
		header("Content-disposition: attachment; filename=" . date("Y-m-d").".csv");
		echo lang('escort_commercial_objective_commercial_label').',';
		echo lang('escort_commercial_objective_rate_label').',';
		echo lang('escort_commercial_objective_actual_label').',';
		echo lang('escort_commercial_objective_price_label');
		echo "\r\n";
		$commercials = $this->escort_commercial_objectives_m->get_all();
		if($commercials){
			foreach ($commercials as $commercial){
				echo $commercial->commercial_username.',';
				echo $commercial->rate_from.'-'.$commercial->rate_to." ".lang('escort_commercial_objective_new_user_label').',';
				echo $commercial->actual_registered." ".lang('escort_commercial_objective_new_user_label').',';
				echo $commercial->price_per_register." ".lang('escort_commercial_objective_per_register_label');
				echo "\r\n";
			}
		}
		
	}
	public function export($id=0){
		$id OR redirect('admin/be_commercial_objective');
		$commercial = $this->escort_commercial_objectives_m->get($id);
		$commercial OR redirect('admin/be_commercial_objective');
		header("Content-type: application/vnd.ms-excel");
		header("Content-disposition: attachment; filename=" . date("Y-m-d").".csv");
		echo lang('escort_commercial_objective_commercial_label').',';
		echo lang('escort_commercial_objective_rate_label').',';
		echo lang('escort_commercial_objective_actual_label').',';
		echo lang('escort_commercial_objective_price_label');
		echo "\r\n";
		//data
		echo $commercial->commercial_username.',';
		echo $commercial->rate_from.'-'.$commercial->rate_to." ".lang('escort_commercial_objective_new_user_label').',';
		echo $commercial->actual_registered." ".lang('escort_commercial_objective_new_user_label').',';
		echo $commercial->price_per_register." ".lang('escort_commercial_objective_per_register_label');
		echo "\r\n";
	}
	public function mark_as_paid(){
		$id = $this->input->post('id');
		$commercial = $this->escort_commercial_objectives_m->get($id);
		$commercial OR die();
		$this->escort_commercial_objectives_m->update($id, array(
			'actual_registered' => 0
		));
		$result = array();
		$result['result'] = true;
		$result['message'] = sprintf(lang('escort_commercial_objective_mark_as_pay_success'), $commercial->commercial_username);
		$this->session->set_flashdata('success', sprintf($this->lang->line('escort_commercial_objective_mark_as_pay_success'), $commercial->commercial_username));
		do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_mark_as_paid_commercial_objective_action', array($id, $commercial->commercial_username));
		echo json_encode($result);
	}
}
